package boot.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import boot.spring.realm.UserRealm;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	UserRealm realm;
	
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		auth.userDetailsService(realm).passwordEncoder(encoder);
    }
	
	protected void configure(HttpSecurity http) throws Exception {
		 http
        .authorizeRequests()
        .antMatchers("/plugins/**","/css/**","/img/**","/js/**").permitAll()
            .anyRequest().authenticated()// 剩下的其它请求,都是登录之后就能访问
            .and()
        .formLogin()
            .loginPage("/login")     //登录页面
            .loginProcessingUrl("/loginvalidate") //登录认证地址
            .defaultSuccessUrl("/index", true)  //登陆成功后的地址
            .permitAll()
            .and()
        .logout().logoutUrl("/logout")
            .permitAll()
            .and().csrf().disable();
	}
	
	
	public static void main(String[] args) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		System.out.println(encoder.encode("1234"));
	}
}
